package com.gengzp.rpc.factory.impl;

import com.gengzp.rpc.constants.RemoteTransactionalConstants;
import com.gengzp.rpc.constants.RpcCommonConstants;
import com.gengzp.rpc.core.RemoteTransactionalHandler;
import com.gengzp.rpc.factory.RpcBeanFactory;
import com.gengzp.rpc.interceptor.RpcHttpRequestInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @ClassName RpcBeanFactoryImpl
 * @Description
 * @Author gengzp
 * @Date 2025/6/1 15:01
 */
@Component
public class RpcBeanFactoryImpl implements RpcBeanFactory {

    @Autowired
    private Map<String, RpcHttpRequestInterceptor> rpcHttpRequestInterceptorMap;

    @Autowired
    private Map<String, RemoteTransactionalHandler> remoteTransactionalHandlerMap;

    @Override
    public RpcHttpRequestInterceptor getRpcHttpRequestInterceptor() {
        if (rpcHttpRequestInterceptorMap.size() == 1) {
            return rpcHttpRequestInterceptorMap.get(RpcCommonConstants.DEFAULT_INTERCEPTOR_BEAN_NAME);
        }
        return rpcHttpRequestInterceptorMap.values().stream()
                .filter(v -> !v.getClass().getName().contains(RpcCommonConstants.DEFAULT_INTERCEPTOR_BEAN_NAME))
                .toList().get(0);
    }

    @Override
    public RemoteTransactionalHandler getRemoteTransactionHandler() {
        if (remoteTransactionalHandlerMap.size() == 1) {
            return remoteTransactionalHandlerMap.get(RemoteTransactionalConstants.REMOTE_TRANSACTION_HANDLER_BEAN_NAME_DEFAULT);
        }
        return remoteTransactionalHandlerMap.values().stream()
                .filter(v -> !v.getClass().getName().contains(RemoteTransactionalConstants.REMOTE_TRANSACTION_HANDLER_BEAN_NAME_DEFAULT))
                .toList().get(0);
    }

}
